package com.leetcode;

import java.util.ArrayList;

/**
 * @BelongsProject: LeetCode
 * @BelongsPackage: com.leetcode
 * @Author: lei
 * @CreateTime: 2024-03-10  10:41
 * @Description: TODO
 * @Version: 1.2
 */
public class 接雨水02 {
    public static void main(String[] args) {
        //int[] arr = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
        int[] arr = {4, 2, 0, 3, 2, 5};
        System.out.println(arr.length);   // 12
        System.out.println(trap(arr));

    }

    /**
     * @description: 此处的想法是按照每个峰点进行切割<峰点就是左右值最大的一个>
     * @author: lei
     * @date: 2024/3/10 11:51
     * @param: [height]
     * @return: int
     **/
    public static int trap(int[] height) {
        ArrayList<Integer> arrayList = new ArrayList<>();
        int resultArea = 0;
        if (height[0] > height[1]) {
            arrayList.add(0);
        }
        for (int i = 1; i < height.length; i++) {
            if ((i == (height.length - 1) && height[i] > height[i - 1])) {
                arrayList.add(i);
                resultArea = getResultArea(height, arrayList, resultArea);
            } else if ((height[i] > height[i - 1]) && (height[i] > height[i + 1])) {
                arrayList.add(i);
                resultArea = getResultArea(height, arrayList, resultArea);
                i = i + 1;
            }
        }
        return resultArea;
    }

    private static int getResultArea(int[] height, ArrayList<Integer> arrayList, int resultArea) {
        if (arrayList.size() == 2) {
            Integer leftIndex = arrayList.get(0);
            Integer rightIndex = arrayList.get(1);
            int width = rightIndex - leftIndex - 1;
            int areaTotal = width * Math.min(height[leftIndex], height[rightIndex]);
            int area = areaTotal - (extraArea(height, leftIndex, rightIndex));
            resultArea += area;
            arrayList.clear();
            arrayList.add(rightIndex);
        }
        return resultArea;
    }

    private static int extraArea(int[] height, Integer leftIndex, Integer rightIndex) {
        int diff = rightIndex - leftIndex - 1;
        int result = 0;
        for (int i = 1; i <= diff; i++) {
            int j = height[leftIndex + i];
            result += j;
        }
        return result;
    }

}
